<template>
	<view v-show="true" class="content">
		<view class="closeWrap">
			<image @tap="toIndex" class="closeImg" src="../../static/img/close.png"></image>
		</view>
		<view class="logoWrap">
			<image class="logo" src="../../static/img/logo.png"></image>
		</view>
		<view class="loginWrap">
			<view class="login">
				<input class="inputs" v-model="phone" placeholder="输入手机号" maxlength="11" placeholder-class="inputPlaceholder" />
			</view>
			<view v-show="!isPhone" class="login">
				<input class="inputs" v-model="password" :password="isEye" placeholder="输入密码" placeholder-class="inputPlaceholder" />
				<image v-if="isEye" @tap="isEye=!isEye" class="eye" src="../../static/img/eye-off.png"></image>
				<image v-else @tap="isEye=!isEye" class="eye" src="../../static/img/eye.png"></image>
			</view>
			<view v-show="isPhone" class="login">
				<input class="inputs" v-model="code" placeholder="输入验证码" placeholder-class="inputPlaceholder" />
				<text v-if="!isCode" @tap="getCode" class="eyeCode">获取验证码</text>
				<view v-else class="eyeCodes">
					<image @tap="code=''" class="icon_close" src="../../static/img/icon_close.png"></image>
					<text style="color: #BFBFBF;font-size: 28rpx;">{{secondsLeft}}秒后重发</text>
				</view>
			</view>
		</view>
		<view class="agreementWrap">
			<radio :checked="isAgree" style="transform: scale(0.7);" @tap="isAgree = !isAgree"></radio>
			<text class="agree">登录即同意</text>
			<text v-for="(item,index ) in agreementList" :key="index" style="display: flex;align-items: center;flex-wrap: wrap;">
				<text style="color: #6B64D3;font-size: 24rpx;"><text v-if="index==agreementList.length-1" class="agree">和</text><text style="color: #6B64D3;font-size: 24rpx;" @tap="touchAgreement(item)">《{{item.agreementTitle}}》</text> <text v-if="index<agreementList.length-2" class="agree">、</text></text>
			</text>
			<text class="agreeInfo">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如未注册，请使用手机验证码或微信登录，登录验证后将自动创建宜趣多资账号(密码登录须设置密码后才能使用)。</text>
		</view>
		<view class="submitWrap">
			<view v-if="!resetting" @tap="login(true,false)" class="submit">
				<text style="font-weight: 700;font-size: 32rpx;color: #F5F5F5;letter-spacing: 2rpx;">{{isPhone?'一键登录':'登录'}}</text>
			</view>
			<view v-else @tap="reset" class="submit">
				<text style="font-weight: 700;font-size: 32rpx;color: #F5F5F5;letter-spacing: 2rpx;">重置密码</text>
			</view>
		</view>
		<view class="codeWrap">
			<text v-if="!isPhone" style="color: #8C8C8C;font-size: 28rpx;" @tap="isPhone=true;loginType='SMS_LOGIN'">手机验证码登录</text>
			<text v-if="!isPhone" style="color: #8C8C8C;font-size: 28rpx;" @tap="reset">忘记密码</text>
			<text v-if="isPhone" style="color: #8C8C8C;font-size: 28rpx;" @tap="isPhone=false;resetting=false;loginType='PWD_LOGIN'">密码登录</text>
		</view>
		<view class="other">
			<text style="color: #8C8C8C;font-size: 26rpx;">其他登录方式</text>
		</view>
		<view class="others">
			<image class="otherImg" @tap="wxLogin" src="../../static/img/wechat.png"></image>
		</view>
	</view>
	<view v-if="isPop" class="popUp">
		<view class="pop">
			<view class="popTitle">
				<text style="font-weight: 700;font-size: 34rpx;color: #262626;">隐私保护说明</text>
			</view>
			<view style="width: 81%;margin-left: 9.5%;">
				<text>
					<text class="popTxt">为保障您的个人权益，登录前请先阅读</text>
					<text v-for="(item,index) in agreementList">
						<text class="agreeTxt" @tap="touchAgreement(item)">《{{item.agreementTitle}}》</text>
						<text class="popTxt" v-if="index<agreementList.length-1">、</text>
					</text>
					<text class="popTxt"> 同意并勾选后再登录。</text>
				</text>
			</view>
			<view class="toAgreeWrap">
				<view @tap="agreeAment" class="toAgrees">
					<text style="font-size: 32rpx;color: #fff;">同意并继续</text>
				</view>
				<view @tap="isPop=false" class="toAgreeNo">
					<text style="font-size: 32rpx;color: #595959;">不同意并退出</text>
				</view>
			</view>
		</view>
	</view>
	<view v-if="isExist" class="popUp">
		<view class="pop" style="height: 350rpx;">
			<view class="popTitle" style="height: 100rpx;">
				<text style="font-weight: 700;font-size: 34rpx;color: #262626;">邀请码（非必填）</text>
			</view>
			<view style="width: 84%;margin-left: 8%;">
				<input class="inputPop" v-model="shareCode" placeholder="请填写邀请码" placeholder-class="inputPlaceholder" />
			</view>
			<view class="existWrap">
				<view @tap="confirmInviteCode(false)" class="left" hover-class="buttonHover">
					<text style="color: #8C8C8C;font-size: 36rpx;">取消</text>
				</view>
				<view @tap="confirmInviteCode(true)" class="right" hover-class="buttonHover">
					<text style="color: #6B64D3;font-size: 36rpx;">确认</text>
				</view>
			</view>
		</view>
	</view>
	<uni-popup ref="popup" type="bottom" border-radius="32rpx 32rpx 0 0">
		<scroll-view class="popupWrap">
			<view class="popupTitle">{{popupTitle}}</view>
			<scroll-view scroll-y="true" style="width: 100%;height: 72vh;margin-bottom: 3vh;">
				<rich-text :nodes="popupContent"></rich-text>
			</scroll-view>
		</scroll-view>
	</uni-popup>
</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import { initPush } from '@/utils/push.ts'
	import { onLoad } from '@dcloudio/uni-app'
	import { userPhoneExist, userLogin, sendSmsCode, queryAgreement, fillShareCode } from '@/utils/api/index.ts'
	import { connectWebsocket } from '@/utils/websocket.ts'
	import { connectIm } from '@/utils/tencent.ts'
	const isEye = ref(true)   //查看密码
	const isAgree = ref(false)  //是否同意了协议
	const isPop = ref(false)   //协议弹窗
	const isPhone = ref(true)  //是否为手机验证码登陆
	const code = ref('')  //手机验证码
	const isCode = ref(false)  //手机验证码获取状态
	const secondsLeft = ref(60)  //验证码倒计时
	const resetting = ref(false)  //是否重置密码
	const isExist = ref(false)
	const phone = ref('') //手机号
	const password = ref('')  //密码
	const shareCode = ref('')
	const comeback = () => {
		uni.navigateBack({
			success: function () {
				
				console.log('执行1')
				uni.$emit('loginSuccess');
				uni.$emit('loginSuccessIndex');
			}
		})
	}
	const toIndex = () => {
		uni.switchTab({
			url: `/pages/index/index`
		})
	}
	// 获取验证码
	const timer = ref(null)
	const smsId = ref('')
	const loginType = ref('SMS_LOGIN')
	const agreementList = ref([])
	const getCode = async () => {
		if (phone.value == '') {
			uni.showToast({
				title: '请填写手机号',
				icon: 'error'
			});
			return
		}
		uni.showLoading({
			title: '请稍后...'
		})
		const res = await sendSmsCode({ data: { phone: phone.value } })
		uni.hideLoading()
		uni.showToast({
			title: '短信发送成功',
			icon: 'success'
		});
		smsId.value = res.data
		isCode.value = true
		secondsLeft.value = 60
		timer.value = setInterval(() => {
			if (secondsLeft.value > 0) {
				secondsLeft.value--;
			} else {
				clearInterval(timer.value!);
				isCode.value = false
				secondsLeft.value = 60
			}
		}, 1000);
	}

	// 密码登录
	const login = async (validExist : boolean, validShareCode : boolean) => {
		isWx.value = false
		if (phone.value == '') {
			uni.showToast({
				title: '请填写手机号',
				icon: 'error'
			});
			return
		}

		if (!/^1[3456789]\d{9}$/.test(phone.value)) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			});
			return
		}
		if (!isPhone.value && password.value == '') {
			uni.showToast({
				title: '请填写密码',
				icon: 'error'
			});
			return
		}
		if (isPhone.value && code.value == '') {
			uni.showToast({
				title: '请填写验证码',
				icon: 'error'
			});
			return
		}
		if (!isAgree.value) {
			isPop.value = true
			return
		}

		const loginData = {
			phone: phone.value,
			code: code.value,
			smsId: smsId.value,
			loginType: loginType.value,
			shareCode: shareCode.value
		}
		if (loginType.value == 'PWD_LOGIN') {
			loginData.code = password.value
		}
		const res = await userLogin({
			data: loginData
		})

		uni.setStorageSync('userInfo', res.data)
		uni.setStorageSync('token', res.data.token)
		connectWebsocket(res.data?.userId)
		initPush()
		connectIm()
		comeback()
	}

	const wxLogin = async () => {
		isWx.value = true
		if (!isAgree.value) {
			isPop.value = true
			return
		}
		uni.showLoading({
			title: '请稍后'
		})

		//微信双开问题，1.5秒自动关闭
		let timerId = setTimeout(function () {
			uni.hideLoading();
		}, 1500);

		uni.login({
			"provider": 'weixin',
			"onlyAuthorize": true, //使用微信登录
			success: async (loginRes) => {
				clearTimeout(timerId); // 取消定时器
				uni.hideLoading()

				const loginData = {
					code: loginRes.code,
					loginType: 'WX_LOGIN'
				}
				const res = await userLogin({
					data: loginData
				})
				if (res.data.resultCode == 1) {
					//需要补充手机号
					uni.navigateTo({
						url: `/pages/fillPhone/index?openid=${res.data.openid}&unionId=${res.data.unionId}`
					})
				} else {
					uni.setStorageSync('userInfo', res.data)
					uni.setStorageSync('token', res.data.token)
					connectWebsocket(res.data?.userId)
					initPush()
					connectIm()
					comeback()
				}
			},
			fail: async (err) => {
				clearTimeout(timerId); // 取消定时器
				uni.hideLoading()

				if (err.code == -8) {
					uni.showToast({
						title: '手机未安装微信!',
						icon: 'error'
					});
				}

			}
		});
	}
	// 重置密码
	const reset = async () => {
		uni.navigateTo({
			url: `/pages/reset/reset`
		})
	}


	const loadAgreement = async () => {
		const res = await queryAgreement({
			data: {
				agreementType: 'LOGIN'
			}
		})
		agreementList.value = res.data
	}

	// 协议触发
	const popup = ref<InstanceType<typeof Popup> | null>(null);
	const popupTitle = ref('')
	const popupContent = ref<any>()
	const touchAgreement = (item : any) => {
		popupTitle.value = item.agreementTitle
		popupContent.value = item.agreementContent
		popup.value.open('bottom')
	}
	const isWx = ref(false)
	const agreeAment = () => {
		isPop.value = false
		isAgree.value = true
		if (isWx.value) {
			wxLogin()
		} else {
			login(false, true)
		}
	}

	const confirmInviteCode = (bool) => {
		if (bool) {
			fillShareCode({ data: { shareCode: shareCode.value } }).then(res => {
				setTimeout(() => {
					uni.showToast({
						title: '填写成功!',
						icon: 'success'
					});
				}, 500)
				isExist.value = false
				comeback()
			})
		} else {
			isExist.value = false
			comeback()
		}
	}

	// 邀请码填写
	onLoad(() => {
		loadAgreement()
	})
</script>
<style scoped>
	.changeBar1 {
		width: 620rpx;
		height: 40rpx;
		background: linear-gradient(149deg, #FFF2FD 0%, #ffcccc 32%, #ff6666 100%);
		margin-left: 38rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;

		.describe {
			width: 100%;
			font-size: 24rpx;
			margin: 0 24rpx;
			text-align: center;
		}
	}

	.content {
		width: 100%;
		padding-top: var(--status-bar-height);
		min-height: 100vh;
		background: url('../../static/img/bj.png') no-repeat;
	}

	.closeWrap {
		width: 100%;
		height: 150rpx;
		display: flex;
		align-items: center;
	}

	.closeImg {
		width: 36rpx;
		height: 36rpx;
		margin-left: 35rpx;
	}

	.logoWrap {
		width: 100%;
		height: 470rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.logo {
		width: 198rpx;
		height: 200rpx;
		border-radius: 15rpx;
		margin-bottom: 25rpx;
	}

	.loginWrap {
		width: 80%;
		height: 220rpx;
		margin-left: 10%;
	}

	.login {
		width: 100%;
		height: 110rpx;
		border-bottom: 1rpx solid #EFEEF1;
		display: flex;
		position: relative;
	}

	.inputPlaceholder {
		color: #CED4DB;
		font-size: 32rpx;
	}

	.inputs {
		width: 100%;
		height: 110rpx;
		box-sizing: border-box;
	}

	.eye {
		width: 36rpx;
		height: 36rpx;
		position: absolute;
		right: 0;
		top: 40rpx;
	}

	.eyeCode {
		height: 36rpx;
		color: #6B64D3;
		position: absolute;
		right: 0;
		top: 40rpx;
	}

	.eyeCodes {
		width: 220rpx;
		height: 80rpx;
		position: absolute;
		right: 0;
		top: 40rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.icon_close {
		width: 32rpx;
		height: 32rpx;
		margin-top: 2rpx;
	}

	.agreementWrap {
		width: 80%;
		margin-top: 10rpx;
		margin-left: 10%;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.agree {
		color: #8C8C8C;
		font-size: 24rpx;
	}

	.agreeInfo {
		margin-top: 10rpx;
		background: linear-gradient(149deg, #ffffff 0%, #e5f2ff 32%, #99ccff 100%);
		color: #8C8C8C;
		font-size: 24rpx;
		padding: 10rpx;
		border-radius: 8rpx;
	}

	.submitWrap {
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.submit {
		width: 638rpx;
		height: 92rpx;
		background: #6B64D3;
		box-shadow: 0rpx 5rpx 24rpx 0rpx rgba(107, 100, 211, 0.3);
		border-radius: 46rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.codeWrap {
		width: 80%;
		height: 82rpx;
		margin-left: 10%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
	}

	.other {
		width: 100%;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20rpx;
	}

	.others {
		width: 100%;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.otherImg {
		width: 72rpx;
		height: 72rpx;
	}

	.popUp {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pop {
		width: 600rpx;
		height: 580rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		position: relative;
	}

	.popTitle {
		width: 100%;
		height: 144rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.popTxt {
		font-size: 28rpx;
		color: #595959;
		letter-spacing: 2rpx;
	}

	.agreeTxt {
		font-size: 28rpx;
		color: #6B64D3;
		letter-spacing: 2rpx;
	}

	.toAgreeWrap {
		width: 100%;
		margin-top: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.toAgrees {
		width: 488rpx;
		height: 88rpx;
		background: #6B64D3;
		border-radius: 22rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.toAgreeNo {
		width: 488rpx;
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.inputPop {
		width: 100%;
		height: 80rpx;
		background: #f4f6fa;
		border-radius: 24rpx;
		padding-left: 20rpx;
	}

	.existWrap {
		width: 100%;
		height: 120rpx;
		position: absolute;
		bottom: 0;
		display: flex;
		flex-direction: row;
	}

	.left {
		width: 50%;
		height: 120rpx;
		border-top: 1rpx solid #ededed;
		border-right: 1rpx solid #ededed;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.right {
		width: 50%;
		height: 120rpx;
		border-top: 1rpx solid #ededed;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 弹窗容器样式 */
	.popupWrap {
		width: 100%;
		height: 80vh;
		padding: 24rpx;
		background-color: #ffffff;
		border-radius: 24rpx 24rpx 0rpx 0rpx;
	}

	/* 公告题目样式 */
	.popupTitle {
		width: 100%;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 16rpx;
		color: #333333;
	}
</style>